import request from '../../utils/request'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartList: [],
    allSelect: false,
    totalMoney: 0
  },

  /**
   * 去往商品详情页
   */
  toGoods(options) {
    let id = options.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/goodsPackage/pages/goods/goods?goodsId=' + id,
    })
  },

  //事件处理函数
  /*点击减号*/
  async bindMinus(options) {
    var that = this;
    let index = options.currentTarget.dataset.id;
    let cartList = this.data.cartList;
    let cartId = cartList[index].id
    if (cartList[index].num == 1) {
      // 如果数量为1再减，则确认是否删除
      wx.showModal({
        // title: '提示',
        content: '确认要删除该商品吗？',
        success: async(res) => {
          if (res.confirm) {
            let result = await request('/cart/delete', {
              cartId
            });
            if (result.code == 200) {
              cartList.splice(index, 1)
              that.setData({
                cartList
              })
              that.onLoad();
            }
            // console.log('用户点击确定')
          } else if (res.cancel) {
            // console.log('用户点击取消')
          }
        }
      })
      return;
    }
    cartList[index].num = --cartList[index].num;
    let num = cartList[index].num
    let id = cartList[index].id
    await request('/cart/put', {
      id,
      num
    }, 'POST');
    // 合计
    let totalMoney = this.totalMoney();
    this.setData({
      cartList,
      totalMoney
    })
    // var num = this.data.num;
    // if (num > 1) {
    //   num--;
    // }
    // var minusStatus = num > 1 ? 'normal' : 'disable';
    // this.setData({
    //   num: num,
    //   minusStatus: minusStatus
    // })
  },
  /*点击加号*/
  async bindPlus(options) {
    let index = options.currentTarget.dataset.id;
    let cartList = this.data.cartList;
    cartList[index].num = ++cartList[index].num;
    let id = cartList[index].id
    let num = cartList[index].num
    let result = await request('/cart/put', {
      id,
      num
    }, 'POST');
    // 合计
    let totalMoney = this.totalMoney();
    this.setData({
      cartList,
      totalMoney
    })
    // var num = this.data.num;
    // num++;
    // var minusStatus = num > 1 ? 'normal' : 'disable';
    // this.setData({
    //   num: num,
    //   minusStatus: minusStatus
    // })
  },
  /*输入框事件*/
  bindManual(options) {
    let num = options.detail.value;
    let numReg = /^\d{1,}$/;
    if (!numReg.test(num)) {
      wx.showToast({
        title: '输出内容违规',
        icon: 'none'
      })
      // this.setData({

      // })
      return false;
    }
    // var num = e.detail.value;
    // var minusStatus = num > 1 ? 'normal' : 'disable';
    // this.setData({
    //   num: num,
    //   minusStatus: minusStatus
    // })
  },

  /**
   * 部分勾选
   */
  cartBindChange(options) {
    let index = options.currentTarget.dataset.id;
    let allSelect = true;
    const cartList = this.data.cartList;
    cartList[index].checked = options.detail.value.length == 0 ? false : true;
    if (options.detail.value.length == 0) {
      allSelect = false;
    } else {
      for (let i = 0; i < cartList.length; i++) {
        if (cartList[i].checked == undefined || cartList[i].checked == false) {
          allSelect = false;
          break;
        }
      }
    }
    // 合计
    let totalMoney = this.totalMoney();
    this.setData({
      cartList,
      allSelect,
      totalMoney
    })
  },
  /**
   * 全选按钮
   */
  allSelectBindChange(options) {
    let checked = options.detail.value.length;
    const cartList = this.data.cartList;
    if (checked == 1) {
      // 如果勾选上
      if (cartList.length != null)
        for (let i = 0; i < cartList.length; i++) {
          cartList[i].checked = true;
        }
    } else {
      // 如果不勾选
      if (cartList.length != null)
        for (let i = 0; i < cartList.length; i++) {
          cartList[i].checked = false;
        }
    }
    // 合计
    let totalMoney = this.totalMoney();
    this.setData({
      cartList,
      allSelect: checked,
      totalMoney
    })
  },

  totalMoney() {
    let totalMoney = 0;
    const cartList = this.data.cartList;
    for (let i = 0; i < cartList.length; i++) {
      if (cartList[i].checked == true)
        totalMoney = totalMoney + cartList[i].price * cartList[i].num
    }
    return totalMoney;
  },

  /**
   * 去结算按钮
   */
  takeOrder() {
    let flag = false;
    let goodsList = [];
    let cartList = this.data.cartList;
    if (cartList.length == 0) {
      wx.showToast({
        title: '亲~您的购物车还没有商品哦，请先选择商品吧~',
        icon: 'none'
      })
      return;
    }
    for (let i = 0; i < cartList.length; i++) {
      if (cartList[i].checked == true) {
        goodsList.push(cartList[i])
        flag = true;
      }
    }
    if (!flag) {
      wx.showToast({
        title: '亲~您的购物车还没有勾选商品哦，请选择商品勾选后再结算吧~',
        icon: 'none'
      })
      return;
    }
    wx.navigateTo({
      url: '/orderPackage/pages/confirmOrder/confirmOrder?goodsInfo=' + JSON.stringify(goodsList)
    })


  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function(options) {
    let that = this;
    // let userInfo = wx.getStorageSync('userInfo');
    // let authorization = wx.getStorageSync('authorization');
    // if (!userInfo || !authorization || userInfo == undefined || authorization == undefined) {
    //   wx.navigateTo({
    //     url: '/pages/auth/auth'
    //   })
    //   return;
    // }
    // 获取购物车列表
    let result = await request('/cart/list', {});
    that.setData({
      cartList: result.data,
      allSelect: false,
      totalMoney: 0
    })
  },

  /**
   * 点击购物车Tab的时候发生的事件
   */
  async onTabItemTap(item) {
    let that = this;
    let userInfo = wx.getStorageSync('userInfo');
    let authorization = wx.getStorageSync('authorization');
    if (!userInfo || !authorization || userInfo == undefined || authorization == undefined) {
      wx.navigateTo({
        url: '/pages/auth/auth'
      })
      return;
    }
    let result = await request('/cart/list', {});
    that.setData({
      cartList: result.data,
      allSelect: false,
      totalMoney: 0
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // this.onLoad()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})